﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using NLog;
using Vit.Common.Extensions;

namespace Vit.Data
{
    public class NLogConnectionVisitor : DbConnectionVisitorBase
    {
        protected Logger logger;

        public NLogConnectionVisitor()
        {
            logger = LogManager.GetCurrentClassLogger();
        }

        public override void OnConnectionStateChange(object sender, StateChangeEventArgs e)
        {
            DbConnection conn = sender as DbConnection;
            logger.Info(string.Format("connection state changing from {0} to {1} [{2}]",
                Enum.GetName(typeof(ConnectionState), e.OriginalState),
                Enum.GetName(typeof(ConnectionState), e.CurrentState),
                conn.ConnectionString));
        }

        public override void OnCommandExecuting(object sender, CommandExecutionEventArgs e)
        {
            logger.Info(string.Format("command executing..."));
        }

        public override void OnCommandExecuted(object sender, CommandExecutionEventArgs e)
        {
            logger.Info(string.Format("command executed, time elapse: {0} seconds", e.Duration.Seconds));
        }

        public override void OnCommandFailed(object sender, CommandExecutionEventArgs e)
        {
            Exception ex = e.Result as Exception;
            logger.Error(string.Format("command executing faild and throws exception : {0}", ex.Message));
        }

        public override void OnTransactionCommit(object sender, TransactionEventArgs e)
        {
            logger.Info(string.Format("transaction committed, affects: {0}", e.AffectedEntities.ToFormatString()));
        }

        public override void OnTransactionRollback(object sender, TransactionEventArgs e)
        {
            logger.Info(string.Format("transaction rollbacked, affects: {0}", e.AffectedEntities.ToFormatString()));
        }
    }
}
